package com.fantasy.httpclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class TestFBL {

	private static HttpClient hC = HttpClients.createDefault();

	private static String txtId;
	private static String txtPW,
		txtPW2,
		txtCode,
		hidKey,
		hidLowerCasePW,
		IEVerison,
		tk,
		isSSL,
		PF,
		hidServerKey,
		detecResTime;
	private static String sessionId;
	//ASP.NET_SessionId=ateg5w2eig2bhx1swtusayfa; path=/; HttpOnly\r\n
	
	
	public static void main(String[] args) {
		getLoginValue();
		//System.out.println(encryptionPW("Aaaa11111", "6073"));
		System.out.println(tk);
		login("SFB1361G03", "Aaaa11111");
	}
	
	public static void login(String acct , String pw){
		txtId = acct;
		txtPW2 = pw;
		txtPW = encryptionPW(pw, txtCode);
		HttpPost hp = new HttpPost("https://www.maxbet.com/ProcessLogin.aspx");
		try {
			addPostParams();
			hp.setEntity(paramEntity);
			setHttpPostHeader(hp);
			HttpResponse response = hC.execute(hp);
			// 打印返回的结果
			HttpEntity entity = response.getEntity();
			Header  head= entity.getContentType();
		    String  bodys= head.toString();
		    System.out.println("**********************************");
		    System.out.println(bodys);
		    System.out.println("session:" + sessionId);
			System.out.println(entity.getContentLength());
			System.out.println(response.getStatusLine().getStatusCode());
			String respContent = EntityUtils.toString(new GzipDecompressingEntity(entity) , "UTF-8").trim();
			System.out.println(respContent);
			System.out.println(sessionId);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static void addPostParams() throws UnsupportedEncodingException{
		HashMap<String , String> params = new HashMap<String , String>();
		params.put("txtId", txtId);
		params.put("txtPW", txtPW);
		params.put("txtPW2", txtPW2);
		params.put("txtCode", txtCode);
		params.put("hidKey", hidKey);
		params.put("hidLowerCasePW", hidLowerCasePW);
		params.put("IEVerison", IEVerison);
		params.put("__tk", tk);
		params.put("IsSSL", isSSL);
		params.put("PF", PF);
		params.put("hidServerKey", hidServerKey);
		params.put("detecResTime", detecResTime);
		params.put("detecas-analysis", "js-enabled@" + (new Date().getTime()));
		addPostParams(params);
	}
	
	private static UrlEncodedFormEntity paramEntity = null;
	
	/**
	 * 提交的参数
	 * @throws UnsupportedEncodingException 
	 * */
	public static void addPostParams(HashMap<String , String> params) throws UnsupportedEncodingException{
		 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		 for (Entry<String, String> param : params.entrySet()) {
			formparams.add(new BasicNameValuePair(param.getKey(), param.getValue()));
		}
		paramEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
	}
	
	
	public static void parseFormValue(String html){
		Document doc = Jsoup.parse(html);
		txtCode = getElemValue(doc, "txtCode");
		isSSL = getElemValue(doc, "IsSSL");
		PF = getElemValue(doc, "PF");
		tk = getElemValue(doc, "__tk");
		IEVerison = getElemValue(doc, "IEVerison");
		hidServerKey = getElemValue(doc, "hidServerKey");
		hidKey = getElemValue(doc, "hidKey");
		hidLowerCasePW = getElemValue(doc, "hidLowerCasePW");
		detecResTime = getElemValue(doc, "detecResTime");
	}
	
	public static String getElemValue(Document doc , String id){
		//System.out.println(doc.html());
		Element elem = doc.getElementById(id);
		//System.out.println(id);
		if(null == elem){
			return "";
		}
		return elem.attr("value");
	}
	
	public static  void setHttpPostHeader(HttpPost hp){
		hp.addHeader("Host","www.maxbet.com");
		hp.addHeader("Connection","keep-alive");
		hp.addHeader("Content length", paramEntity.getContentLength() + "");
		hp.addHeader("Cache-Control","max-age=0");
		hp.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		hp.addHeader("Origin","http://www.maxbet.com");
		hp.addHeader("Upgrade-Insecure-Requests","1");
		hp.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
		hp.addHeader("Content-Type","application/x-www-form-urlencoded");
		hp.addHeader("Referer","http://www.maxbet.com/Default.aspx");
		hp.addHeader("Accept-Encoding","gzip, deflate");
		hp.addHeader("Accept-Language","zh-CN,zh;q=0.8");
		hp.addHeader("Cookie","KeepOdds-b14460248c547cf81cd8b17f0883e6b2=no;"
				+ "OddsType_POTH31EQ02=4;"
				+ "dct=a5359e07542c5ee9da27b97f0e6332e6;"
				+ "Wel_SFB1361G03_=1;"
				+ "visid_incap_981972=IauEFOBuT+aB67DR4jLv5C4iPFgAAAAAQUIPAAAAAAAnPXZrZ84m7hLwR+AvafXG;"
				+ "visid_incap_1014031=ekuQrvXbSb2yvWcQ+BYDX2AP/lgAAAAAQUIPAAAAAACrgbavA1HREQUQqbAGYDR5;"
				+ "MSPlatform=2;"
				+ "ASP.NET_SessionId=" + sessionId + ";"
				+ "LangKey=cs;"
				+ "nlbi_981962=muWwAqNNPh1ANuVX0tnbwwAAAABj7hak1+PPTCO/zzkZOea+;"
				+ "_ga=GA1.2.2097610561.1480335872;"
				+ "_gat=1;"
				+ "visid_incap_981962=wYcZhHDXSNG1PbI2VZP5DwAiPFgAAAAAQUIPAAAAAADGUKfLc5krqlN0aDXjpOoW;"
				+ "incap_ses_635_981962=xzq7EobZUjdvmvGsN/nPCIGgAFkAAAAAmUbrleXyX8w9EfBE8P4L6Q==;"
				+ "");
	}
	
	public static  void setHttpGetHeader(HttpGet hg){
		hg.addHeader("Host","www.maxbet.com");
		hg.addHeader("Connection","keep-alive");
		hg.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		hg.addHeader("Upgrade-Insecure-Requests","1");
		hg.addHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36");
		hg.addHeader("Accept-Encoding","gzip, deflate, sdch");
		hg.addHeader("Accept-Language","zh-CN,zh;q=0.8");
		hg.addHeader("Cookie","KeepOdds-b14460248c547cf81cd8b17f0883e6b2=no; OddsType_POTH31EQ02=4; dct=a5359e07542c5ee9da27b97f0e6332e6; Wel_SFB1361G03_=1; visid_incap_981962=wYcZhHDXSNG1PbI2VZP5DwAiPFgAAAAAQUIPAAAAAADGUKfLc5krqlN0aDXjpOoW; visid_incap_981972=IauEFOBuT+aB67DR4jLv5C4iPFgAAAAAQUIPAAAAAAAnPXZrZ84m7hLwR+AvafXG; visid_incap_1014031=ekuQrvXbSb2yvWcQ+BYDX2AP/lgAAAAAQUIPAAAAAACrgbavA1HREQUQqbAGYDR5;LangKey=cs;MSPlatform=2; _ga=GA1.2.2097610561.1480335872");
		hg.addHeader("Accept-Language","zh-CN,zh;q=0.8");
	}
	
	public static void putHeader(HttpResponse response){
		Header[] aa = response.getAllHeaders();
		System.out.println("ALL HEADER");
		for (Header header : aa) {
			System.out.println(header.getName() + ":" + header.getValue());
		}
	}
	
	public static void getLoginValue(){
		
		String res = "";
		HttpGet hg = new HttpGet("http://www.maxbet.com/Default.aspx");
		setHttpGetHeader(hg);
		
		try {
			hC.execute(hg);
			
			HttpResponse response = hC.execute(hg);
			HttpEntity entity = response.getEntity();
			//System.out.println(response.getStatusLine().getStatusCode());
			if(response.getStatusLine().getStatusCode() == 404){
				System.out.println("  页面不存在404");
			}
			putHeader(response);
			getSessionId(response.getFirstHeader("Set-Cookie").getValue());
			String respContent = EntityUtils.toString(entity , "UTF-8").trim();
			System.out.println("-----------------------------------");
			//System.out.println(respContent);
			System.out.println("-----------------------------------");
			res = respContent;
			//System.out.println(respContent);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		parseFormValue(res);
	}
	
	private static void getSessionId(String cookie){
		sessionId = cookie.substring(0 ,cookie.indexOf(";")).replace("ASP.NET_SessionId=", "");
	}
	
	 /**
	  *  CFSKey = CFS(pwobj.value);
        EnCryptData = CFSKey + codeobj.value;
        pwobj.value = MD5(EnCryptData);
	  * */
	  public static String encryptionPW(String pw , String codeValue) {
	    ScriptEngineManager manager = new ScriptEngineManager();
	    ScriptEngine engine = manager.getEngineByName("js");
	    String res = "";
	    try {
	      engine.eval("function WordToHex(e){var t,n,a=\"\",o=\"\";for(n=0;3>=n;n++)t=e>>>8*n&255,o=\"0\"+t.toString(16),a+=o.substr(o.length-2,2);return a}var MD5=function(e){function t(e,t){return e<<t|e>>>32-t}function n(e,t){var n,a,o,r,i;return o=2147483648&e,r=2147483648&t,n=1073741824&e,a=1073741824&t,i=(1073741823&e)+(1073741823&t),n&a?2147483648^i^o^r:n|a?1073741824&i?3221225472^i^o^r:1073741824^i^o^r:i^o^r}function a(e,t,n){return e&t|~e&n}function o(e,t,n){return e&n|t&~n}function r(e,t,n){return e^t^n}function i(e,t,n){return t^(e|~n)}function l(e,o,r,i,l,d,s){return e=n(e,n(n(a(o,r,i),l),s)),n(t(e,d),o)}function d(e,a,r,i,l,d,s){return e=n(e,n(n(o(a,r,i),l),s)),n(t(e,d),a)}function s(e,a,o,i,l,d,s){return e=n(e,n(n(r(a,o,i),l),s)),n(t(e,d),a)}function m(e,a,o,r,l,d,s){return e=n(e,n(n(i(a,o,r),l),s)),n(t(e,d),a)}function u(e){for(var t,n=e.length,a=n+8,o=(a-a%64)/64,r=16*(o+1),i=Array(r-1),l=0,d=0;n>d;)t=(d-d%4)/4,l=d%4*8,i[t]=i[t]|e.charCodeAt(d)<<l,d++;return t=(d-d%4)/4,l=d%4*8,i[t]=i[t]|128<<l,i[r-2]=n<<3,i[r-1]=n>>>29,i}function c(e){e=e.replace(/\\r\\n/g,\"\\n\");for(var t=\"\",n=0;n<e.length;n++){var a=e.charCodeAt(n);128>a?t+=String.fromCharCode(a):a>127&&2048>a?(t+=String.fromCharCode(a>>6|192),t+=String.fromCharCode(63&a|128)):(t+=String.fromCharCode(a>>12|224),t+=String.fromCharCode(a>>6&63|128),t+=String.fromCharCode(63&a|128))}return t}var f,p,v,g,y,h,b,C,S,O=Array(),B=7,E=12,_=17,w=22,F=5,I=9,T=14,x=20,M=4,L=11,k=16,$=23,P=6,A=10,H=15,N=21;for(e=c(e),O=u(e),h=1732584193,b=4023233417,C=2562383102,S=271733878,f=0;f<O.length;f+=16)p=h,v=b,g=C,y=S,h=l(h,b,C,S,O[f+0],B,3614090360),S=l(S,h,b,C,O[f+1],E,3905402710),C=l(C,S,h,b,O[f+2],_,606105819),b=l(b,C,S,h,O[f+3],w,3250441966),h=l(h,b,C,S,O[f+4],B,4118548399),S=l(S,h,b,C,O[f+5],E,1200080426),C=l(C,S,h,b,O[f+6],_,2821735955),b=l(b,C,S,h,O[f+7],w,4249261313),h=l(h,b,C,S,O[f+8],B,1770035416),S=l(S,h,b,C,O[f+9],E,2336552879),C=l(C,S,h,b,O[f+10],_,4294925233),b=l(b,C,S,h,O[f+11],w,2304563134),h=l(h,b,C,S,O[f+12],B,1804603682),S=l(S,h,b,C,O[f+13],E,4254626195),C=l(C,S,h,b,O[f+14],_,2792965006),b=l(b,C,S,h,O[f+15],w,1236535329),h=d(h,b,C,S,O[f+1],F,4129170786),S=d(S,h,b,C,O[f+6],I,3225465664),C=d(C,S,h,b,O[f+11],T,643717713),b=d(b,C,S,h,O[f+0],x,3921069994),h=d(h,b,C,S,O[f+5],F,3593408605),S=d(S,h,b,C,O[f+10],I,38016083),C=d(C,S,h,b,O[f+15],T,3634488961),b=d(b,C,S,h,O[f+4],x,3889429448),h=d(h,b,C,S,O[f+9],F,568446438),S=d(S,h,b,C,O[f+14],I,3275163606),C=d(C,S,h,b,O[f+3],T,4107603335),b=d(b,C,S,h,O[f+8],x,1163531501),h=d(h,b,C,S,O[f+13],F,2850285829),S=d(S,h,b,C,O[f+2],I,4243563512),C=d(C,S,h,b,O[f+7],T,1735328473),b=d(b,C,S,h,O[f+12],x,2368359562),h=s(h,b,C,S,O[f+5],M,4294588738),S=s(S,h,b,C,O[f+8],L,2272392833),C=s(C,S,h,b,O[f+11],k,1839030562),b=s(b,C,S,h,O[f+14],$,4259657740),h=s(h,b,C,S,O[f+1],M,2763975236),S=s(S,h,b,C,O[f+4],L,1272893353),C=s(C,S,h,b,O[f+7],k,4139469664),b=s(b,C,S,h,O[f+10],$,3200236656),h=s(h,b,C,S,O[f+13],M,681279174),S=s(S,h,b,C,O[f+0],L,3936430074),C=s(C,S,h,b,O[f+3],k,3572445317),b=s(b,C,S,h,O[f+6],$,76029189),h=s(h,b,C,S,O[f+9],M,3654602809),S=s(S,h,b,C,O[f+12],L,3873151461),C=s(C,S,h,b,O[f+15],k,530742520),b=s(b,C,S,h,O[f+2],$,3299628645),h=m(h,b,C,S,O[f+0],P,4096336452),S=m(S,h,b,C,O[f+7],A,1126891415),C=m(C,S,h,b,O[f+14],H,2878612391),b=m(b,C,S,h,O[f+5],N,4237533241),h=m(h,b,C,S,O[f+12],P,1700485571),S=m(S,h,b,C,O[f+3],A,2399980690),C=m(C,S,h,b,O[f+10],H,4293915773),b=m(b,C,S,h,O[f+1],N,2240044497),h=m(h,b,C,S,O[f+8],P,1873313359),S=m(S,h,b,C,O[f+15],A,4264355552),C=m(C,S,h,b,O[f+6],H,2734768916),b=m(b,C,S,h,O[f+13],N,1309151649),h=m(h,b,C,S,O[f+4],P,4149444226),S=m(S,h,b,C,O[f+11],A,3174756917),C=m(C,S,h,b,O[f+2],H,718787259),b=m(b,C,S,h,O[f+9],N,3951481745),h=n(h,p),b=n(b,v),C=n(C,g),S=n(S,y);var D=WordToHex(h)+WordToHex(b)+WordToHex(C)+WordToHex(S);return D.toLowerCase()},CFS=function(e){function t(e){for(var t=\"\",n=1;n<=e.length;n++)t+=e.charAt(n-1).charCodeAt(0);var a=new Number(t);return t=a.toString(16)}var n,a,o=30;if(n=o-e.length,n>1)for(var r=1;n>=r;r++)e+=String.fromCharCode(21);for(var i=new Number(1),l=1;o>=l;l++)a=o+e.charAt(l-1).charCodeAt(0)*l,i*=a;var d=new Number(i.toPrecision(15));e=d.toString().toUpperCase();for(var s=\"\",m=1;m<=e.length;m++)s+=t(e.substring(m-1,m+2));for(var u=\"\",m=20;m<=s.length-18;m+=2)u+=s.charAt(m-1);return u.toUpperCase()};");
	      String cfsKey = (String) engine.eval("CFS('" + pw + "')");
	      res = (String) engine.eval("MD5('" + cfsKey + codeValue + "')");
	    } catch (Exception e) {
	      e.printStackTrace();
	      System.out.println("加密密码出错");
	    }
	    return res;
	  }
	
	
	
}
